import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:laoba_menu/views/product-detail/Detail.dart';
import 'dart:convert';
import './Data.dart';
import './CategoryItem.dart';

class CategoryListPage extends StatefulWidget {
  CategoryListPage({
    Key key,
    @required this.id, // 接收一个text参数
    @required this.name, // 接收一个text参数
  }) : super(key: key);
  final String name;
  final int id;

  @override
  CategoryListPageWidget createState() =>
      new CategoryListPageWidget(this.id, this.name);
}

class CategoryListPageWidget extends State<CategoryListPage> {
  String name;
  int id;
  CategoryListPageWidget(this.id, this.name);
  Dio dio = Dio();
  Response response;
  List dataList = [];

  Future getData() async {
    final String url = 'http://127.0.0.1:7001/cook/findByCategoryId';
    final res = await dio.get(url, queryParameters: {'category_id': this.id});
    var data = jsonDecode(res.toString());
    dataList = data['data']
        .map((i) => CategoryList.fromJson(i.cast<String, dynamic>()))
        .toList();
    setState(() {
      getWidgetList();
    });
  }

  @override
  initState() {
    super.initState();
    getData();
  }

  List<Widget> getWidgetList() {
    return dataList.map((item) => getItemContainer(item)).toList();
  }

  Widget getItemContainer(item) {
    return GestureDetector(
      child: CategoryItem(
          id: item.id,
          name: item.name,
          desc: item.desc,
          cover: item.cover,
          create_time: item.create_time,
          favorite_count: item.favorite_count),
      onTap: () => jumpCookDetail(item.id, item.cover, item.name, item.desc),
    );
  }

  void jumpCookDetail(int id, String cover, String name, String desc) {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return CookDetail(id: id, cover: cover, name: name, desc: desc);
    }));
  }

  Future<String> mockNetworkData() async {
    return Future.delayed(Duration(seconds: 2), () => "两秒钟loading");
  }

  // 空
  Widget enptyWidget() {
    return Center(child: Text("暂无数据"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(name),
        ),
        body: Center(
            child: FutureBuilder<String>(
                future: mockNetworkData(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  // 请求已结束
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      // 请求失败，显示错误
                      return Text("Error: ${snapshot.error}");
                    } else {
                      // 请求成功，显示数据
                      return dataList.length > 0
                          ? ListView(
                              children: getWidgetList(),
                            )
                          : enptyWidget();
                    }
                  } else {
                    // 请求未结束，显示loading
                    return CircularProgressIndicator();
                  }
                })));
  }
}
